﻿Imports System.Security.Cryptography
Imports System.Text

'Encriptacion TripleDes
'http://www.dreamincode.net/forums/topic/171440-encrypting-xml/

'Encoding.UTF8
'http://jharaphula.com/how-to-encrypt-rc2-md5-triple-des-byte-128-a-string-using-vb-net


'Algoritmo triple DES, con clave MD5, modo ECB, codificacion Base64
Public Class CriptoTripleDES

    Private DES As New TripleDESCryptoServiceProvider
    Private mDataUTF8 As Boolean

    Public Sub New(ByVal key As String)
        Me.New(key, False, True)
    End Sub

    Public Sub New(ByVal key As String, ByVal keyUTF8 As Boolean, ByVal dataUTF8 As Boolean)
        If keyUTF8 Then
            DES.Key = CriptoMD5Util.MD5HashUTF8(key)
        Else
            DES.Key = CriptoMD5Util.MD5Hash(key)
        End If
        DES.Mode = CipherMode.ECB
        mDataUTF8 = dataUTF8
    End Sub

    Public Function encrypt(ByVal data As String) As String
        Return Convert.ToBase64String(encryptToBytes(data))
    End Function
    'data: string to encrypt 
    Public Function encryptToBytes(ByVal data As String) As Byte()
        Dim buffer As Byte()
        If mDataUTF8 Then
            buffer = Encoding.UTF8.GetBytes(data)
        Else
            buffer = ASCIIEncoding.ASCII.GetBytes(data)
        End If
        Return DES.CreateEncryptor().TransformFinalBlock(buffer, 0, buffer.Length)
    End Function

    Public Function decrypt(ByVal data As String) As String
        Return decrypt(Convert.FromBase64String(data))
    End Function

    'data: encrypted string
    Public Function decrypt(ByVal data() As Byte) As String
        Try
            Dim Buffer As Byte() = data
            Dim dataDesencriptada As Byte() = DES.CreateDecryptor().TransformFinalBlock(Buffer, 0, Buffer.Length)
            If mDataUTF8 Then
                Return Encoding.UTF8.GetString(dataDesencriptada)
            Else
                Return ASCIIEncoding.ASCII.GetString(dataDesencriptada)
            End If
        Catch
            MessageBox.Show("Wrong Key Number, decryption not available!")
            Return Nothing
        End Try
    End Function

End Class
